package com.SystemcurrentTimeMillis性能问题;

import java.util.concurrent.CountDownLatch;

/**可见，并发调用System.currentTimeMillis()一百次，耗费的时间是单线程调用一百次的250倍。如果单线程的调用频次增加（比如达到每毫秒数次的地步），也会观察到类似的情况。
 * 实际上在极端情况下，System.currentTimeMillis()的耗时甚至会比创建一个简单的对象实例还要多
 * @author zhangsulei
 *
 */
public class CurrentTimeMillisPerfDemo {

	private static final int COUNT = 100;

	public static void main(String[] args) throws Exception {

		long beginTime = System.nanoTime();

		for (int i = 0; i < COUNT; i++) {

			System.currentTimeMillis();

		}

		long elapsedTime = System.nanoTime() - beginTime;

		System.out.println("100 System.currentTimeMillis() serial calls: " + elapsedTime + " ns");

		CountDownLatch startLatch = new

		CountDownLatch(1);

		CountDownLatch endLatch = new

		CountDownLatch(COUNT);

		for (int i = 0; i < COUNT; i++) {

			new

			Thread(() -> {

				try {

					startLatch.await();

					System.currentTimeMillis();

				} catch (InterruptedException e) {

					e.printStackTrace();

				} finally {

					endLatch.countDown();

				}

			}).start();

		}

		beginTime = System.nanoTime();

		startLatch.countDown();

		endLatch.await();

		elapsedTime = System.nanoTime() - beginTime;

		System.out.println("100 System.currentTimeMillis() parallel calls: " + elapsedTime + " ns");

	}

}
